const http = require("./http");
const nodeEcharts = require("node-echarts");
const { javaServerAddress, token, companyId, colors } = require("../config");

const apiAddress = `${javaServerAddress}/monthlyReport`;

const httpOperations = {
  url: apiAddress,
  method: "get",
  headers: {
    Authorization: token
  },
  qs: {
    companyId
  }
};

const getCount = arr => {
  // type = 1-6
  let newArr,
    newArrSort = arr.sort((a, b) => {
      return a.type - b.type;
      // return b.type-a.type
    });
  newArr = newArrSort.map(t => {
    return t.count;
  });
  return newArr;
};

const getMax = (str, array, array1) => {
  let newArray = null;
  try {
    newArray = [
      array.find(t => {
        return t.des === str;
      }).count,
      array1.find(t => {
        return t.des === str;
      }).count
    ];
  } catch (e) {
    if (e) {
      return [];
    }
  }
  return Math.max.apply(null, newArray) + 1;
};

const makeRandom = (min, max) => {
  return Math.floor(Math.random() * (max - min)) + min;
};

const makePoint = size => {
  let doubleArr = [];
  for (let i = 0; i < size; i++) {
    doubleArr.push([makeRandom(0, 100), makeRandom(0, 100)]);
  }
  return doubleArr;
};

// 隐患综合指数分析
async function yinHuanZongHeZhiShuFenXi({
  queryMonthList,
  lastMonthList,
  filename,
  folder
}) {
  const path = `${filename}.png`;
  let _folder = null;
  if (folder.endsWith("//") || folder.endsWith("/")) {
    _folder = folder;
  } else {
    _folder = folder + "//";
  }
  return new Promise(resolve => {
    const lastMonthArr = getCount(lastMonthList);
    const currentMonthArr = getCount(queryMonthList);
    const dianyaMax = getMax("电压", queryMonthList, lastMonthList),
      dianliuMax = getMax("电流", queryMonthList, lastMonthList),
      wenduMax = getMax("温度", queryMonthList, lastMonthList),
      bupinghengMax = getMax("不平衡度", queryMonthList, lastMonthList),
      xieboMax = getMax("不平衡度", queryMonthList, lastMonthList),
      zhongxinMax = getMax("中性线", queryMonthList, lastMonthList),
      loudianMax = getMax("漏电", queryMonthList, lastMonthList),
      option = {
        color: [...colors],
        animation: false,
        // title: {
        //   text: "综合评估"
        // },
        tooltip: {
          trigger: "item",
          confine: true
        },
        legend: {
          data: ["本月", "上月"],
          left: 10,
          top: "center"
        },
        radar: {
          name: {
            textStyle: {
              color: "#fff",
              backgroundColor: "#999",
              borderRadius: 3,
              padding: [3, 5]
            }
          },
          indicator: [
            {
              name: "电压",
              max: dianyaMax
            },
            {
              name: "电流",
              max: dianliuMax
            },
            {
              name: "温度",
              max: wenduMax
            },
            {
              name: "不平衡度",
              max: bupinghengMax
            },
            {
              name: "谐波",
              max: xieboMax
            },
            {
              name: "中性线",
              max: zhongxinMax
            },
            {
              name: "漏电",
              max: loudianMax
            }
          ]
        },
        series: [
          {
            name: "隐患综合指数",
            type: "radar",
            data: [
              {
                value: currentMonthArr,
                name: "本月"
              },
              {
                value: lastMonthArr,
                name: "上月"
              }
            ]
          }
        ]
      };

    nodeEcharts({
      width: 500,
      height: 300,
      option,
      path: _folder + path,
      enableAutoDispose: true
    });
    resolve(path);
  });
}

async function drawChart(sizeError, sizeNormal, filename, folder) {
  const path = `${filename}.png`;
  let _folder = null;
  if (folder.endsWith("//") || folder.endsWith("/")) {
    _folder = folder;
  } else {
    _folder = folder + "//";
  }
  return new Promise(resolve => {
    const option = {
      color: [...colors],
      animation: false,
      legend: {
        data: ["异常", "正常"],
        left: 5,
        top: 20
      },
      xAxis: [
        {
          type: "value",
          splitLine: {
            show: false
          }
        },
        {
          type: "value",
          axisLine: {
            onZero: false
          }
        }
      ],
      yAxis: [
        {
          type: "value",
          splitLine: {
            show: false
          }
        },
        {
          type: "value",
          axisLine: {
            onZero: false
          }
        }
      ],
      series: [
        {
          name: "异常",
          symbolSize: 8,
          type: "scatter",
          data: makePoint(sizeError),
          itemStyle: {
            color: "red"
          }
        },
        {
          name: "正常",
          symbolSize: 8,
          type: "scatter",
          data: makePoint(sizeNormal - sizeError),
          itemStyle: {
            color: "#64F703"
          }
        }
      ]
    };
    nodeEcharts({
      width: 500,
      height: 500,
      option,
      path: _folder + path,
      enableAutoDispose: true
    });
    resolve(path);
  });
}

async function drawPie(online, offline, filename, folder) {
  const path = `${filename}.png`;
  let _folder = null;
  if (folder.endsWith("//") || folder.endsWith("/")) {
    _folder = folder;
  } else {
    _folder = folder + "//";
  }
  return new Promise(resolve => {
    const option = {
      color: ["red", "#8DBA23"],
      animation: false,
      title: {
        text: "监测设备运行状态统计",
        x: "center"
      },
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        orient: "vertical",
        left: "left",
        data: ["离线设备", "在线设备"]
      },
      series: [
        {
          name: "运行状态",
          type: "pie",
          radius: "55%",
          center: ["50%", "60%"],
          data: [
            {
              value: offline,
              name: "离线设备"
            },
            {
              value: online,
              name: "在线设备"
            }
          ],
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            }
          }
        }
      ]
    };

    nodeEcharts({
      width: 500,
      height: 300,
      option,
      path: _folder + path,
      enableAutoDispose: true
    });

    resolve(path);
  });
}

async function genMonthly106Images(companyId, folder) {
  const filenamePrefix = companyId.replace(/-/g, "") + "-";
  try {
    const _httpOperations = {
      ...httpOperations,
      qs: {
        companyId
      }
    };
    const { statusCode, body } = await http(apiAddress, _httpOperations);
    if (statusCode === 200 && body) {
      const resData = JSON.parse(body);
      const {
        data: {
          queryMonthList,
          lastMonthList,
          headerData,
          onLineSize,
          offLineSize
        }
      } = resData;

      const sizeNormal =
        headerData && headerData.deviceSize ? headerData.deviceSize : 0;

      if (Array.isArray(queryMonthList)) {
        let r0 = null;
        if (Array.isArray(lastMonthList)) {
          r0 = await yinHuanZongHeZhiShuFenXi({
            queryMonthList,
            lastMonthList,
            filename: filenamePrefix + "41",
            folder
          });
        }

        // 电压
        const dianyaData = queryMonthList.find(t => t.type === 1);

        // 电流
        const dianliuData = queryMonthList.find(t => t.type === 2);

        // 温度
        const wenduData = queryMonthList.find(t => t.type === 3);

        // 不平衡
        const bupinghengData = queryMonthList.find(t => t.type === 4);

        //  谐波
        const xieboData = queryMonthList.find(t => t.type === 5);

        //  漏电
        const loudianData = queryMonthList.find(t => t.type === 7);

        // 中性线
        const zhongxinData = queryMonthList.find(t => t.type === 6);

        const r1 = await drawChart(
          dianyaData.errorDeviceSize2,
          sizeNormal,
          filenamePrefix + "42",
          folder
        );
        const r2 = await drawChart(
          dianyaData.errorDeviceSize1,
          sizeNormal,
          filenamePrefix + "43",
          folder
        );
        const r3 = await drawChart(
          dianliuData.count,
          sizeNormal,
          filenamePrefix + "44",
          folder
        );
        const r4 = await drawChart(
          wenduData.count,
          sizeNormal,
          filenamePrefix + "45",
          folder
        );
        const r5 = await drawChart(
          bupinghengData.errorDeviceSize1,
          sizeNormal,
          filenamePrefix + "46",
          folder
        );
        const r6 = await drawChart(
          bupinghengData.errorDeviceSize2,
          sizeNormal,
          filenamePrefix + "47",
          folder
        );
        const r7 = await drawChart(
          xieboData.count,
          sizeNormal,
          filenamePrefix + "48",
          folder
        );
        const r8 = await drawChart(
          loudianData.count,
          sizeNormal,
          filenamePrefix + "49",
          folder
        );
        const r9 = await drawChart(
          zhongxinData.count,
          sizeNormal,
          filenamePrefix + "50",
          folder
        );
        const r10 = await drawPie(
          onLineSize ? onLineSize : 0,
          offLineSize ? offLineSize : 0,
          filenamePrefix + "51",
          folder
        );
        const allFolderAddress = [r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10];
        return allFolderAddress;
      }
    }
  } catch (error) {
    return Promise.reject({
      code: 400,
      error: error
    });
  }
}

module.exports = genMonthly106Images;
